import Taro, { getStorageSync } from '@tarojs/taro'
import { delLoginInfoStore } from '@/utils/index'
import store from '@/store'
import { loginFun } from './auth'

let isRefreshing = false
let subscribers = []
let isFirst = false
let newToken = null

function onAccessTokenFetched() {
  subscribers.forEach((callback) => callback())
  subscribers = []
}
function addSubscriber(callback) {
  subscribers.push(callback)
}

export default function request(options, callback) {
  const defaultOpts = {
    url: '',
    method: 'GET'
  }
  options = Object.assign({}, defaultOpts, options)
  const { token } = store.user
  // const newTime = new Date().getTime()
  const accessToken = newToken || token || getStorageSync('token')
  // const tokenExpire = accessTokenExpire || getStorageSync('accessTokenExpire')
  const header = Object.assign({}, { Authorization: accessToken }, options.header)
  const requestOptions = {
    url: options.url,
    header,
    data: options.data,
    method: options.method.toUpperCase()
  }

  return new Promise((resolve, reject) => {
    // if (
    //   options.url.indexOf('/login/login-bycode') < 1 &&
    //   ((accessToken && accessToken === '') || (accessToken && newTime > tokenExpire * 1000 && !isRefreshing))
    // ) {
    //   addSubscriber(() => {
    //     request(
    //       {
    //         url: options.url,
    //         header: options.header,
    //         data: options.data,
    //         method: options.method.toUpperCase()
    //       },
    //       resolve
    //     )
    //   })
    //   if (!isFirst) {
    //     isFirst = true
    //     loginFun(false)
    //       .then((loginData) => {
    //         if (loginData.accessToken) {
    //           newToken = loginData.accessToken
    //           onAccessTokenFetched()
    //         }
    //       })
    //       .catch(() => {
    //         Taro.showToast({ title: '登录失败，请刷新小程序重新登录', icon: 'none', duration: 2000 })
    //       })
    //   }
    // } else {
    Taro.request({
      ...requestOptions,
      fail(err) {
        err?.data?.title && Taro.showToast({ title: err.data?.title, icon: 'none', duration: 2000 })
        reject(err)
      },
      complete(response) {
        if (newToken) {
          newToken = null
          isFirst = false
        }
        if (callback) return callback(response.data)
        if (response?.statusCode === 401) {
          addSubscriber(() => {
            request(
              {
                url: options.url,
                header: options.header,
                data: options.data,
                method: options.method.toUpperCase()
              },
              resolve
            )
          })
          if (!isRefreshing) {
            isRefreshing = true
            delLoginInfoStore()
            loginFun(true)
              .then((loginData) => {
                if (loginData.accessToken) {
                  onAccessTokenFetched()
                  const refreshTimer = setTimeout(() => {
                    isRefreshing = false
                    refreshTimer && clearTimeout(refreshTimer)
                  }, 5000)
                }
              })
              .catch(() => {
                Taro.showToast({ title: '登录失败，请刷新小程序重新登录', icon: 'none', duration: 2000 })
                resolve(response)
              })
          }
        } else if (response?.statusCode !== 200) {
          response?.data?.title && Taro.showToast({ title: response.data?.title, icon: 'none', duration: 2000 })
          resolve(response)
        } else if (response?.statusCode === 200) {
          resolve(response.data)
        }
      }
    })
    // }
  })
}
